﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Models;
using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.View
{
    public partial class UcStandardSourceEfficiencyMeasurement : UserControl
    {
        private int channelCount = AppConfig.ChannelCount;
        #region 字段定义
        private List<ChannelData> channelDataList;

        // 添加控件引用字段
        private UITextBox txtMeasurementCount;
        private UITextBox txtMeasurementTime;
        private UITextBox[,] txtBackgroundValues; // [通道索引, 0=α, 1=β]
        private UITextBox[,] txtStandardSourceValues; // [通道索引, 0=α比活度, 1=α质量, 2=β比活度, 3=β质量]
        private GlobalPresetData globalPreset;
        private UITextBox txtSampleDiskArea;

        // α 和 β 选择框
        private UICheckBox chkAlphaEnabled;
        private UICheckBox chkBetaEnabled;

        // 新增：测量类型标识（各个组件需要设置不同的值）
        protected virtual string MeasurementType { get; set; } = "StandardSourceEfficiency";
        #endregion
        #region 测量结果显示
        // 测量类型显示名称映射
        protected static readonly Dictionary<string, string> MeasurementTypeDisplayNames = new Dictionary<string, string>
{
    {"Background", "本底测量"},
    {"WorkingSourceEfficiency", "工作源效率测量"},
    {"StandardSourceEfficiency", "标准源效率测量"},
    {"WaterSample", "水样品测量"},
    {"BioSample", "生物样品测量"},
    {"GasSample", "气体样品测量"},
    {"EnvSample", "环境样品测量"}
};
        // ================================
        // 3. 通用化的查看最新结果方法
        // ================================

        /// <summary>
        /// 查看最新结果按钮点击事件 - 通用版本
        /// 根据组件的测量类型显示对应的最新多轮测量结果
        /// </summary>
        private async void BtnViewLatestResult_Click(object sender, EventArgs e)
        {
            string originalText = "查看最新结果"; // 在方法开始处
            try
            {
                var clickedButton = sender as UIButton;
                string measurementType = clickedButton?.Tag?.ToString() ?? MeasurementType;
                string displayName = GetMeasurementTypeDisplayName(measurementType);

                // 显示加载提示
                originalText = clickedButton?.Text ?? "查看最新结果";
                if (clickedButton != null)
                {
                    clickedButton.Enabled = false;
                    clickedButton.Text = "加载中...";
                }

                // 查找该类型的最新测量数据
                var latestMeasurementData = await FindLatestMeasurementByType(measurementType);

                if (latestMeasurementData == null)
                {
                    UIMessageBox.ShowWarning($"暂无{displayName}结果！\n请先完成{displayName}后再查看结果。");
                    return;
                }

                // 打开MultiRoundResultForm显示结果
                var resultForm = new MultiRoundResultForm(latestMeasurementData);
                resultForm.ShowDialog(this);

                System.Diagnostics.Debug.WriteLine($"已显示{displayName}最新测量结果，测量时间：{latestMeasurementData.StartTime:yyyy-MM-dd HH:mm:ss}");
            }
            catch (Exception ex)
            {
                string displayName = GetMeasurementTypeDisplayName(MeasurementType);
                UIMessageBox.ShowError($"查看{displayName}最新结果失败：{ex.Message}");
                System.Diagnostics.Debug.WriteLine($"查看{displayName}最新结果失败: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                var clickedButton = sender as UIButton;
                if (clickedButton != null)
                {
                    clickedButton.Enabled = true;
                    clickedButton.Text = originalText;
                }
            }
        }

        /// <summary>
        /// 根据测量类型查找最新的测量数据 - 通用方法
        /// </summary>
        /// <param name="measurementType">测量类型（如"WaterSample", "BioSample"等）</param>
        /// <returns>最新的测量数据，如果不存在返回null</returns>
        private async Task<MultiRoundMeasurementData> FindLatestMeasurementByType(string measurementType)
        {
            MultiRoundMeasurementData latestData = null;
            DateTime latestTime = DateTime.MinValue;

            try
            {
                // 遍历所有通道查找指定类型的测量数据
                for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                {
                    try
                    {
                        var measurementData = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);

                        if (measurementData != null && measurementData.StartTime > latestTime)
                        {
                            latestTime = measurementData.StartTime;
                            latestData = measurementData;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"检查通道 {channelIndex + 1} {measurementType} 数据时出错: {ex.Message}");
                        // 继续检查其他通道
                    }
                }

                // 记录查找结果
                if (latestData != null)
                {
                    string displayName = GetMeasurementTypeDisplayName(measurementType);
                    System.Diagnostics.Debug.WriteLine($"找到最新{displayName}数据：");
                    System.Diagnostics.Debug.WriteLine($"  测量时间: {latestData.StartTime:yyyy-MM-dd HH:mm:ss} - {latestData.EndTime:yyyy-MM-dd HH:mm:ss}");
                    System.Diagnostics.Debug.WriteLine($"  总轮数: {latestData.TotalRounds}");
                    System.Diagnostics.Debug.WriteLine($"  参与通道: {latestData.ChannelResults.Count} 个");
                    System.Diagnostics.Debug.WriteLine($"  测量ID: {latestData.MeasurementId}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"未找到任何{measurementType}测量数据");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"查找最新{measurementType}测量数据失败: {ex.Message}");
                throw;
            }

            return latestData;
        }

        /// <summary>
        /// 获取测量类型的显示名称
        /// </summary>
        /// <param name="measurementType">英文测量类型</param>
        /// <returns>中文显示名称</returns>
        private string GetMeasurementTypeDisplayName(string measurementType)
        {
            return MeasurementTypeDisplayNames.ContainsKey(measurementType)
                ? MeasurementTypeDisplayNames[measurementType]
                : measurementType;
        }
        #endregion

        #region 初始化
        public UcStandardSourceEfficiencyMeasurement()
        {
            InitializeComponent();
            globalPreset = GlobalPresetManager.LoadGlobalPreset(); // 加载全局预设
            LoadChannelData();

            BuildPreset();
            BuildSpacer(1);
            BuildWork();
            BuildSpacer(3);
            BuildDuration();
            BuildSpacer(5, 26);
            BuildButtons();
            LoadMeasurementSettings();         // 加载测量设置
            LoadPresetConditions(); // 加载预设条件
        }
        private int inputHeight = 28;
        // 预设条件（几何因子 + 2π表面发射率，全部是输入框）
        private void BuildPreset()
        {
            var group = new UIGroupBox
            {
                Text = "预设条件",
                Dock = DockStyle.Top,
                AutoSize = true,
                Padding = new Padding(8),
                Margin = new Padding(16, 12, 16, 0)
            };

            var tbl = new TableLayoutPanel
            {
                ColumnCount = channelCount + 1,
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 120));
            for (int i = 0; i < channelCount; i++)
                tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / channelCount));

            // *** 重要：在这里初始化控件数组 ***
            txtStandardSourceValues = new UITextBox[channelCount, 4];

            int row = 0;

            // Row0: 样品盘面积
            tbl.Controls.Add(new UILabel()
            {
                Text = "样品盘面积mm²",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleLeft,
                MinimumSize = new Size(0, 28)
            }, 0, row);

            txtSampleDiskArea = new UITextBox()  // *** 保存引用 ***
            {
                Text = "200",
                Width = 60,
                Dock = DockStyle.Left,
                Margin = new Padding(6, 4, 0, 4)
            };
            tbl.Controls.Add(txtSampleDiskArea, 1, row);
            row++;

            // Row1: 标准源比活度/质量 标题
            var lblSurface = new UILabel()
            {
                Text = "标准源比活度/质量",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleLeft,
                MinimumSize = new Size(0, 28)
            };
            tbl.Controls.Add(lblSurface, 0, row);
            tbl.SetColumnSpan(lblSurface, 2);
            row++;

            // Row2: 通道标签
            tbl.Controls.Add(new UILabel() { Text = "", Dock = DockStyle.Fill }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                tbl.Controls.Add(new UILabel()
                {
                    Text = $"通道{i + 1}",
                    Dock = DockStyle.Left,
                    AutoSize = true,
                    Margin = new Padding(6, 0, 0, 4),
                    TextAlign = ContentAlignment.MiddleLeft
                }, i + 1, row);
            }
            row++;

            // Row3: α - Bq/g（添加选择框）
            var alphaBqPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.LeftToRight,
                AutoSize = true,
                Margin = new Padding(0)
            };

            chkAlphaEnabled = new UICheckBox
            {
                Text = "",
                Checked = true,
                AutoSize = true,
                Margin = new Padding(0, 0, 5, 0)
            };

            var lblAlphaBq = new UILabel
            {
                Text = "α - Bq/g",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Margin = new Padding(0)
            };

            alphaBqPanel.Controls.Add(chkAlphaEnabled);
            alphaBqPanel.Controls.Add(lblAlphaBq);
            tbl.Controls.Add(alphaBqPanel, 0, row);

            for (int i = 0; i < channelCount; i++)
            {
                txtStandardSourceValues[i, 0] = new UITextBox()  // *** 保存引用 ***
                {
                    Text = "12.5",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Margin = new Padding(6, 4, 0, 4)
                };
                tbl.Controls.Add(txtStandardSourceValues[i, 0], i + 1, row);
            }
            row++;

            // Row4: α - mg（无需单独选择框，与 α - Bq/g 共用选择框）
            tbl.Controls.Add(new UILabel()
            {
                Text = "     α - mg",  // 缩进与上面对齐
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleRight
            }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                txtStandardSourceValues[i, 1] = new UITextBox()  // *** 保存引用 ***
                {
                    Text = "20",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Margin = new Padding(6, 4, 0, 4)
                };
                tbl.Controls.Add(txtStandardSourceValues[i, 1], i + 1, row);
            }
            row++;

            // Row5: β - Bq/g（添加选择框）
            var betaBqPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.LeftToRight,
                AutoSize = true,
                Margin = new Padding(0)
            };

            chkBetaEnabled = new UICheckBox
            {
                Text = "",
                Checked = true,
                AutoSize = true,
                Margin = new Padding(0, 0, 5, 0)
            };

            var lblBetaBq = new UILabel
            {
                Text = "β - Bq/g",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Margin = new Padding(0)
            };

            betaBqPanel.Controls.Add(chkBetaEnabled);
            betaBqPanel.Controls.Add(lblBetaBq);
            tbl.Controls.Add(betaBqPanel, 0, row);

            for (int i = 0; i < channelCount; i++)
            {
                txtStandardSourceValues[i, 2] = new UITextBox()  // *** 保存引用 ***
                {
                    Text = "14.4",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Enabled = true,
                    Margin = new Padding(6, 4, 0, 4)
                };
                tbl.Controls.Add(txtStandardSourceValues[i, 2], i + 1, row);
            }
            row++;

            // Row6: β - mg（无需单独选择框，与 β - Bq/g 共用选择框）
            tbl.Controls.Add(new UILabel()
            {
                Text = "     β - mg",  // 缩进与上面对齐
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleRight
            }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                txtStandardSourceValues[i, 3] = new UITextBox()  // *** 保存引用 ***
                {
                    Text = "20",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Enabled = true,
                    Margin = new Padding(6, 4, 0, 4)
                };
                tbl.Controls.Add(txtStandardSourceValues[i, 3], i + 1, row);
            }

            // 绑定选择框事件：两行α绑定，两行β绑定
            chkAlphaEnabled.CheckedChanged += (s, e) =>
            {
                for (int i = 0; i < channelCount; i++)
                {
                    // 启用/禁用 α 的两行（Bq/g 和 mg）
                    if (txtStandardSourceValues[i, 0] != null)
                        txtStandardSourceValues[i, 0].Enabled = chkAlphaEnabled.Checked;
                    if (txtStandardSourceValues[i, 1] != null)
                        txtStandardSourceValues[i, 1].Enabled = chkAlphaEnabled.Checked;
                }
            };

            chkBetaEnabled.CheckedChanged += (s, e) =>
            {
                for (int i = 0; i < channelCount; i++)
                {
                    // 启用/禁用 β 的两行（Bq/g 和 mg）
                    if (txtStandardSourceValues[i, 2] != null)
                        txtStandardSourceValues[i, 2].Enabled = chkBetaEnabled.Checked;
                    if (txtStandardSourceValues[i, 3] != null)
                        txtStandardSourceValues[i, 3].Enabled = chkBetaEnabled.Checked;
                }
            };

            group.Controls.Add(tbl);
            this.outerLayout.Controls.Add(group, 0, 0);
        }



        private void BuildWork()
        {
            var group = new UIGroupBox
            {
                Text = "工作条件",
                Dock = DockStyle.Top,
                AutoSize = true,
                Padding = new Padding(8),
                Margin = new Padding(16, 0, 16, 0)
            };

            var tbl = new TableLayoutPanel
            {
                ColumnCount = channelCount + 1,
                RowCount = 4,
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 120));
            for (int i = 0; i < channelCount; i++)
                tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / channelCount));

            // 初始化本底值控件数组
            txtBackgroundValues = new UITextBox[channelCount, 2];

            int row = 0;

            // Row0: 本底/CPS 标题
            var lblCpsTitle = new UILabel
            {
                Text = "本底/CPS：",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleRight
            };
            tbl.Controls.Add(lblCpsTitle, 0, row);
            row++;

            // Row1: 通道表头
            tbl.Controls.Add(new UILabel() { Text = "", Dock = DockStyle.Fill }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                tbl.Controls.Add(new UILabel
                {
                    Text = $"通道{i + 1}",
                    Dock = DockStyle.Left,
                    AutoSize = true,
                    Margin = new Padding(6, 0, 0, 0),
                    TextAlign = ContentAlignment.MiddleLeft
                }, i + 1, row);
            }
            row++;

            // Row2: α行
            tbl.Controls.Add(new UILabel { Text = "α", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                txtBackgroundValues[i, 0] = new UITextBox
                {
                    Text = "0",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Height = inputHeight,
                    Enabled = false,
                    ReadOnly = true,
                    BackColor = Color.FromArgb(240, 240, 240)
                };
                tbl.Controls.Add(txtBackgroundValues[i, 0], i + 1, row);
            }
            row++;

            // Row3: β行
            tbl.Controls.Add(new UILabel { Text = "β", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                txtBackgroundValues[i, 1] = new UITextBox
                {
                    Text = "0",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Height = inputHeight,
                    Enabled = false,
                    ReadOnly = true,
                    BackColor = Color.FromArgb(240, 240, 240)
                };
                tbl.Controls.Add(txtBackgroundValues[i, 1], i + 1, row);
            }

            group.Controls.Add(tbl);
            this.outerLayout.Controls.Add(group, 0, 2);
        }
        // 测量时长
        private void BuildDuration()
        {
            var group = new UIGroupBox
            {
                Text = "测量时长",
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                Padding = new Padding(12),
                Margin = new Padding(16, 8, 16, 0)
            };

            var table = new TableLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                ColumnCount = 4,
                RowCount = 1,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            table.ColumnStyles.Clear();
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));

            table.RowStyles.Clear();
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            var lblCount = new UILabel
            {
                Text = "测量次数",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };

            // 保存控件引用
            txtMeasurementCount = new UITextBox
            {
                Name = "txtMeasurementCount",
                Text = "1",
                Width = 80,
                Margin = new Padding(0, 2, 24, 2),
                Enabled = true,
                ReadOnly = false,
                BackColor = Color.White,
                Anchor = AnchorStyles.Left
            };

            var lblTime = new UILabel
            {
                Text = "测量时间(min)",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };

            // 保存控件引用
            txtMeasurementTime = new UITextBox
            {
                Name = "txtMeasurementTime",
                Text = "5",
                Width = 80,
                Margin = new Padding(0, 2, 0, 2),
                Enabled = true,
                ReadOnly = false,
                BackColor = Color.White,
                Anchor = AnchorStyles.Left
            };

            table.Controls.Add(lblCount, 0, 0);
            table.Controls.Add(txtMeasurementCount, 1, 0);
            table.Controls.Add(lblTime, 2, 0);
            table.Controls.Add(txtMeasurementTime, 3, 0);

            group.Controls.Add(table);
            this.outerLayout.Controls.Add(group, 0, 6);

            group.Height = group.PreferredSize.Height;
        }
        private void BuildSpacer(int row, int height = 12)
        {
            var spacer = new Panel { Height = height, Dock = DockStyle.Top, BackColor = Color.Transparent };
            this.outerLayout.Controls.Add(spacer, 0, row);
        }
        // 创建按钮并绑定事件
        private void BuildButtons()
        {
            // 按钮总容器（设计器里已有 panelButtons），统一 Top+AutoSize
            panelButtons.AutoSize = true;
            panelButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            panelButtons.Dock = DockStyle.Top;
            panelButtons.Padding = new Padding(0);
            panelButtons.Margin = new Padding(16, 8, 16, 0);

            panelButtons.Controls.Clear();

            var panel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,                 // 关键：不要 Fill
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = false,                 // 单行显示按钮
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            var btnStartMeasurement = new UIButton
            {
                Text = "开始测量",
                Width = 110,
                Height = 36,
                Margin = new Padding(60, 0, 0, 0)
            };
            btnStartMeasurement.Click += BtnStartMeasurement_Click;

            var btnCancel = new UIButton
            {
                Text = "取消",
                Width = 110,
                Height = 36,
                Margin = new Padding(32, 0, 0, 0)
            };
            btnCancel.Click += BtnCancel_Click;


            // 查看最新结果按钮
            var btnViewLatestResult = new UIButton
            {
                Text = "查看最新结果",
                Width = 130,
                Height = 36,
                Margin = new Padding(20, 0, 0, 0),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Tag = MeasurementType // 使用Tag存储测量类型
            };
            btnViewLatestResult.Click += BtnViewLatestResult_Click;
            panel.Controls.Add(btnViewLatestResult);
            panel.Controls.Add(btnStartMeasurement);
            panel.Controls.Add(btnCancel);

            panelButtons.Controls.Add(panel);

            // 放到第 8 行（AutoSize）
            this.outerLayout.Controls.Add(panelButtons, 0, 8);
        }

        public event Action<int, int> OnMeasurementStarted;  // 测量次数和时间

        private void BtnStartMeasurement_Click(object sender, EventArgs e)
        {
            SavePresetConditions();
            try
            {
                // 验证至少选择了 α 或 β
                if (chkAlphaEnabled != null && chkBetaEnabled != null)
                {
                    if (!chkAlphaEnabled.Checked && !chkBetaEnabled.Checked)
                    {
                        UIMessageBox.ShowWarning("请至少选择一种测量类型（α 或 β）");
                        return;
                    }
                }

                // 使用保存的控件引用，而不是查找
                if (txtMeasurementCount == null || txtMeasurementTime == null)
                {
                    UIMessageBox.ShowError("界面控件未正确初始化。");
                    return;
                }

                if (!int.TryParse(txtMeasurementCount.Text, out int measurementCount) ||
                    !int.TryParse(txtMeasurementTime.Text, out int measurementTime))
                {
                    UIMessageBox.ShowError("请输入有效的数字。");
                    return;
                }

                // === 新增：保存工作条件到配置文件（实现双向绑定）===
                bool workConditionSaved = SaveWorkConditionToConfig();
                if (!workConditionSaved)
                {
                    var result = MessageBox.Show("工作条件保存失败，是否继续进行测量？",
                                               "保存提示",
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                OnMeasurementStarted?.Invoke(measurementCount, measurementTime);

                // 构建测量类型信息
                string measurementTypes = "";
                if (chkAlphaEnabled != null && chkBetaEnabled != null)
                {
                    if (chkAlphaEnabled.Checked && chkBetaEnabled.Checked)
                    {
                        measurementTypes = "α 和 β";
                    }
                    else if (chkAlphaEnabled.Checked)
                    {
                        measurementTypes = "α";
                    }
                    else if (chkBetaEnabled.Checked)
                    {
                        measurementTypes = "β";
                    }
                }

                // 更新成功消息，包含测量类型和工作条件保存状态
                string successMessage = $"开始标准源效率测量：次数 {measurementCount}, 时间 {measurementTime} 分钟";
                if (!string.IsNullOrEmpty(measurementTypes))
                {
                    successMessage += $"\n测量类型：{measurementTypes}";
                }
                if (workConditionSaved)
                {
                    successMessage += "\n工作条件已保存到配置文件";
                }

                UIMessageBox.ShowSuccess(successMessage);

                this.Parent?.Hide();
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"启动测量时发生错误：{ex.Message}");
            }
        }       /// <summary>
                /// 刷新通道数据和界面显示
                /// </summary>
                /// <summary>
                /// 刷新通道数据和界面显示
                /// </summary>
        public void RefreshData()
        {
            try
            {
                LoadChannelData();
                LoadMeasurementSettings();

                // 强制刷新界面
                this.Invalidate();
                this.Update();

                System.Diagnostics.Debug.WriteLine("UcStandardSourceEfficiencyMeasurement 数据和界面已刷新");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"刷新数据失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 加载通道数据
        /// </summary>
        private void LoadChannelData()
        {
            try
            {
                channelDataList = ChannelDataManager.LoadAllChannelData();

                // 确保有足够的通道数据
                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载通道数据失败：{ex.Message}");
                // 初始化默认数据
                channelDataList = new List<ChannelData>();
                for (int i = 0; i < channelCount; i++)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = i });
                }
            }
        }

        /// <summary>
        /// 加载测量设置到界面
        /// </summary>
        private void LoadMeasurementSettings()
        {
            try
            {
                if (channelDataList.Count > 0)
                {
                    var workCondition = channelDataList[0].WorkConditions;

                    // 使用保存的控件引用，避免查找
                    if (txtMeasurementCount != null)
                        txtMeasurementCount.Text = workCondition.MeasurementCycle.ToString();

                    if (txtMeasurementTime != null)
                        txtMeasurementTime.Text = workCondition.MeasurementTime.ToString("0.#");

                    // 加载各通道的本底数据
                    if (txtBackgroundValues != null)
                    {
                        for (int i = 0; i < channelCount && i < channelDataList.Count; i++)
                        {
                            var channelWorkCondition = channelDataList[i].WorkConditions;
                            if (txtBackgroundValues[i, 0] != null)
                                txtBackgroundValues[i, 0].Text = channelWorkCondition.AlphaBackground.ToString("0.######");
                            if (txtBackgroundValues[i, 1] != null)
                                txtBackgroundValues[i, 1].Text = channelWorkCondition.BetaBackground.ToString("0.######");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载测量设置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存工作条件数据到配置文件（实现双向绑定）
        /// 从界面控件读取数据并保存到配置文件
        /// </summary>
        private bool SaveWorkConditionToConfig()
        {
            try
            {
                // 保存测量设置（所有通道使用相同值）
                if (txtMeasurementCount != null &&
                    int.TryParse(txtMeasurementCount.Text, out int measurementCycle))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementCycle = measurementCycle;
                    }
                }

                if (txtMeasurementTime != null &&
                    double.TryParse(txtMeasurementTime.Text, out double measurementTime))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementTime = measurementTime;
                    }
                }

                // 保存到文件
                bool saved = ChannelDataManager.SaveAllChannelData(channelDataList);

                if (saved && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[标准源效率测量] 工作条件已保存到配置文件");
                }

                return saved;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[标准源效率测量] 保存工作条件失败: {ex.Message}");
                return false;
            }
        }
        // 取消按钮点击事件
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            // 取消测量时，关闭控件或弹窗
            this.Parent?.Hide(); ;  // 关闭父窗体或控件
        }

        // 加载预设条件方法
        private void LoadPresetConditions()
        {
            try
            {
                // 加载全局样品盘面积
                if (txtSampleDiskArea != null)
                    txtSampleDiskArea.Text = globalPreset.SampleDiskArea.ToString();

                // 加载各通道的标准源数据
                for (int i = 0; i < channelCount && i < channelDataList.Count; i++)
                {
                    var channelPreset = channelDataList[i].PresetConditions;

                    if (txtStandardSourceValues[i, 0] != null)
                        txtStandardSourceValues[i, 0].Text = channelPreset.AlphaSpecificActivity.ToString();

                    if (txtStandardSourceValues[i, 1] != null)
                        txtStandardSourceValues[i, 1].Text = channelPreset.AlphaMass.ToString();

                    if (txtStandardSourceValues[i, 2] != null)
                        txtStandardSourceValues[i, 2].Text = channelPreset.BetaSpecificActivity.ToString();

                    if (txtStandardSourceValues[i, 3] != null)
                        txtStandardSourceValues[i, 3].Text = channelPreset.BetaMass.ToString();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载预设条件失败: {ex.Message}");
            }
        }

        // 保存预设条件方法
        private bool SavePresetConditions()
        {
            try
            {
                // 保存全局样品盘面积
                if (!double.TryParse(txtSampleDiskArea?.Text, out double sampleDiskArea))
                {
                    UIMessageBox.ShowError("样品盘面积数据格式错误");
                    return false;
                }
                globalPreset.SampleDiskArea = sampleDiskArea;
                GlobalPresetManager.SaveGlobalPreset(globalPreset);

                // 保存各通道数据（根据选择框状态）
                bool alphaEnabled = chkAlphaEnabled?.Checked ?? true;
                bool betaEnabled = chkBetaEnabled?.Checked ?? true;

                for (int i = 0; i < channelCount; i++)
                {
                    var channelData = channelDataList[i];

                    // 只验证和保存选中的类型
                    if (alphaEnabled)
                    {
                        // 验证 α 数据（两行：Bq/g 和 mg）
                        if (!double.TryParse(txtStandardSourceValues[i, 0]?.Text, out double alphaActivity))
                        {
                            UIMessageBox.ShowError($"通道 {i + 1} 的 α 比活度（Bq/g）数据格式错误");
                            txtStandardSourceValues[i, 0]?.Focus();
                            return false;
                        }
                        if (!double.TryParse(txtStandardSourceValues[i, 1]?.Text, out double alphaMass))
                        {
                            UIMessageBox.ShowError($"通道 {i + 1} 的 α 质量（mg）数据格式错误");
                            txtStandardSourceValues[i, 1]?.Focus();
                            return false;
                        }

                        // 保存 α 数据
                        channelData.PresetConditions.AlphaSpecificActivity = alphaActivity;
                        channelData.PresetConditions.AlphaMass = alphaMass;
                    }

                    if (betaEnabled)
                    {
                        // 验证 β 数据（两行：Bq/g 和 mg）
                        if (!double.TryParse(txtStandardSourceValues[i, 2]?.Text, out double betaActivity))
                        {
                            UIMessageBox.ShowError($"通道 {i + 1} 的 β 比活度（Bq/g）数据格式错误");
                            txtStandardSourceValues[i, 2]?.Focus();
                            return false;
                        }
                        if (!double.TryParse(txtStandardSourceValues[i, 3]?.Text, out double betaMass))
                        {
                            UIMessageBox.ShowError($"通道 {i + 1} 的 β 质量（mg）数据格式错误");
                            txtStandardSourceValues[i, 3]?.Focus();
                            return false;
                        }

                        // 保存 β 数据
                        channelData.PresetConditions.BetaSpecificActivity = betaActivity;
                        channelData.PresetConditions.BetaMass = betaMass;
                    }

                    ChannelDataManager.SaveChannelData(i, channelData);
                }

                // 打印保存信息
                if (AppConfig.LogPrint == 1)
                {
                    string savedTypes = "";
                    if (alphaEnabled && betaEnabled)
                        savedTypes = "α 和 β";
                    else if (alphaEnabled)
                        savedTypes = "α";
                    else if (betaEnabled)
                        savedTypes = "β";

                    Console.WriteLine($"[标准源效率测量] 已保存预设条件：{savedTypes}");
                }

                return true;
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存预设条件失败: {ex.Message}");
                return false;
            }
        }

        #region 计算
        /// <summary>
        /// 获取样品盘面积
        /// </summary>
        public double GetSampleDiskArea()
        {
            try
            {
                if (globalPreset != null)
                {
                    return globalPreset.SampleDiskArea;
                }

                // 如果全局预设为空，尝试重新加载
                globalPreset = GlobalPresetManager.LoadGlobalPreset();
                return globalPreset?.SampleDiskArea ?? 200; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取样品盘面积失败: {ex.Message}");
                return 200; // 返回默认值
            }
        }

        /// <summary>
        /// 获取指定通道的α比活度
        /// </summary>
        public double GetAlphaSpecificActivity(int channelIndex)
        {
            try
            {
                if (channelDataList != null && channelIndex >= 0 && channelIndex < channelDataList.Count)
                {
                    return channelDataList[channelIndex].PresetConditions?.AlphaSpecificActivity ?? 12.5;
                }
                return 12.5; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的α比活度失败: {ex.Message}");
                return 12.5;
            }
        }

        /// <summary>
        /// 获取指定通道的β比活度
        /// </summary>
        public double GetBetaSpecificActivity(int channelIndex)
        {
            try
            {
                if (channelDataList != null && channelIndex >= 0 && channelIndex < channelDataList.Count)
                {
                    return channelDataList[channelIndex].PresetConditions?.BetaSpecificActivity ?? 14.4;
                }
                return 14.4; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的β比活度失败: {ex.Message}");
                return 14.4;
            }
        }

        /// <summary>
        /// 获取指定通道的α源质量
        /// </summary>
        public double GetAlphaSourceMass(int channelIndex)
        {
            try
            {
                if (channelDataList != null && channelIndex >= 0 && channelIndex < channelDataList.Count)
                {
                    return channelDataList[channelIndex].PresetConditions?.AlphaMass ?? 20;
                }
                return 20; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的α源质量失败: {ex.Message}");
                return 20;
            }
        }

        /// <summary>
        /// 获取指定通道的β源质量
        /// </summary>
        public double GetBetaSourceMass(int channelIndex)
        {
            try
            {
                if (channelDataList != null && channelIndex >= 0 && channelIndex < channelDataList.Count)
                {
                    return channelDataList[channelIndex].PresetConditions?.BetaMass ?? 20;
                }
                return 20; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的β源质量失败: {ex.Message}");
                return 20;
            }
        }

        /// <summary>
        /// 获取指定通道的平均源质量（α和β质量的平均值）
        /// </summary>
        public double GetAverageSourceMass(int channelIndex)
        {
            try
            {
                double alphaMass = GetAlphaSourceMass(channelIndex);
                double betaMass = GetBetaSourceMass(channelIndex);
                return (alphaMass + betaMass) / 2.0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的平均源质量失败: {ex.Message}");
                return 20;
            }
        }

        /// <summary>
        /// 获取所有通道的α比活度数组
        /// </summary>
        public double[] GetAllAlphaSpecificActivities()
        {
            double[] activities = new double[channelCount];
            for (int i = 0; i < channelCount; i++)
            {
                activities[i] = GetAlphaSpecificActivity(i);
            }
            return activities;
        }

        /// <summary>
        /// 获取所有通道的β比活度数组
        /// </summary>
        public double[] GetAllBetaSpecificActivities()
        {
            double[] activities = new double[channelCount];
            for (int i = 0; i < channelCount; i++)
            {
                activities[i] = GetBetaSpecificActivity(i);
            }
            return activities;
        }

        /// <summary>
        /// 获取所有通道的平均源质量数组
        /// </summary>
        public double[] GetAllAverageSourceMasses()
        {
            double[] masses = new double[channelCount];
            for (int i = 0; i < channelCount; i++)
            {
                masses[i] = GetAverageSourceMass(i);
            }
            return masses;
        }

        /// <summary>
        /// 刷新数据并重新加载预设条件
        /// </summary>
        public void RefreshPresetData()
        {
            try
            {
                LoadChannelData();
                globalPreset = GlobalPresetManager.LoadGlobalPreset();
                LoadPresetConditions();
                System.Diagnostics.Debug.WriteLine("UcStandardSourceEfficiencyMeasurement 预设数据已刷新");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"刷新预设数据失败: {ex.Message}");
            }
        }
        #endregion
    }
}
#endregion